<template>
  <div>
    <ElDivider>表单权限设置</ElDivider>
    <ElTable :data="formPermList" row-key="id">
      <ElTableColumn label="字段名" prop="label" show-overflow-tooltip></ElTableColumn>
      <ElTableColumn label="只读" width="80px">
        <template #header>
          <ElCheckbox v-model="readonlyAll" @change="handleReadonlyChange">只读</ElCheckbox>
        </template>
        <template #default="scope">
          <ElCheckbox v-model="scope.row.readonly"></ElCheckbox>
        </template>
      </ElTableColumn>
      <ElTableColumn label="隐藏" width="80px">
        <template #header>
          <ElCheckbox v-model="hiddenAll" @change="handleHiddenChange">隐藏</ElCheckbox>
        </template>
        <template #default="scope">
          <ElCheckbox v-model="scope.row.hidden"></ElCheckbox>
        </template>
      </ElTableColumn>
    </ElTable>
  </div>
</template>

<script setup lang="ts" name="PagePanel">
import { ElDivider, ElTable, ElTableColumn, ElCheckbox } from "element-plus";
import { computed, inject, ref, watch } from "vue";
import { flatWidget } from "../../util/common";
const props = defineProps({
  node: {
    type: Object
  }
});
const formPermList = computed(() => {
  if (!props.node!.formPermList) {
    props.node!.formPermList = [];
  }
  return props.node!.formPermList;
});
const designer = inject("designer");
const pageList = computed(() => designer.value.global.pageList || []);
const handlePageChange = pageId => {
  if (!!pageId) {
    for (const page of pageList.value) {
      if (page.id === pageId) {
        const widgetList = flatWidget(page.pageJson.widgetList);
        const formWidgetList = widgetList.filter(widget => !!widget.formItemProps);
        const permList = formWidgetList.map(formWidget => {
          let readonly = false;
          let hidden = false;
          for (const perm of formPermList.value) {
            if (perm.id === formWidget.id) {
              readonly = !!perm.readonly;
              hidden = !!perm.hidden;
            }
          }
          return {
            id: formWidget.id,
            column: formWidget.formItemProps.props,
            label: formWidget.formItemProps.label,
            readonly: readonly,
            hidden: hidden
          };
        });
        props.node!.formPermList = permList;
        return;
      }
    }
  }
  props.node!.formPermList = [];
};
watch(
  () => props.node!.pageId,
  value => {
    handlePageChange(value);
  },
  { immediate: true }
);
const readonlyAll = ref(false);
const hiddenAll = ref(false);

const handleReadonlyChange = value => {
  for (const formPerm of formPermList.value) {
    formPerm.readonly = value;
  }
};
const handleHiddenChange = value => {
  for (const formPerm of formPermList.value) {
    formPerm.hidden = value;
  }
};
</script>

<style lang="scss" scoped></style>
